<?php
/**
 * This file is part of the Yacms (http://www.yacms.org)
 * Copyright (c) 2019 gylr0505 (http://www.yacms.org)
 *
 * Author: 鬼一浪人 <gylr0505@163.com>
 *
 * DateTime: 19-10-24 下午11:32
 * Description:
 */
 
declare(strict_types = 1);

namespace App\Template;

class ParamsBag
{
    private $params = [];

    /**
     * @var string 请求消息模板发送的url
     */
    private $url = 'https://api.q.qq.com/api/json/template/send?access_token=:access_token';
    /**
     * @var string 接口调用凭证
     */
    private $accessToken = '';

    /**
     * @var string 来自小程序提供商的后台的模板消息id，这里来自数据库设定值
     */
    private $templateId = '';

    /**
     * @var string  发送模板消息的传参数，我们系统来自form_ids表
     */
    private $formId = '';

    /**
     * @var string 接收者，这里是来自用户表中的open_id值
     */
    private $touser = '';

    /**
     * @var string 与touser相当
     */
    private $openId = '';

    /**
     * @var string 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。
     *             该字段不填则模板无跳转。
     */
    private $page = '';

    /**
     * @var object 模板内容，不填则下发空模板。
     */
    private $data = [];

    /**
     * @var string 模板需要放大的关键词，不填则默认无放大。本类中没有处理该值，需要时再启用
     */
    private $emphasisKeyword = '';

    /**
     * @var int 用户主键id
     */
    private $userId = 0;

    /**
     * @var string
     */
    private $appId = '';

    /**
     * @var array 占位符预替换参数
     */
    private $placeholder_params = [];

    public function __construct($params = [])
    {
        $this->init($params);
    }

    /**
     * @param array $params
     */
    private function init($params = [])
    {
        foreach ($params as $property => $value){
            $this->setProperty($property, $value);
        }
    }

    /**
     * @param $property
     * @param null $value
     */
    public function setProperty($property, $value = null)
    {
        if (isset($this->$property)){
            $this->$property = $value;
            $this->params[$property] = $value;
        }
    }

    /**
     * @param $property
     * @return |null
     */
    public function getProperty($property)
    {
        return $this->$property ?? null;
    }

    /**
     * 发起请求时，需用到的参数
     * @return array
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    public function generatorRequestParams()
    {
        if (!$this->formId){
            $this->formId = TemplateService::getFirstFromIdByOpenId($this->openId);
        }

        if (!$this->formId){
            return [];
        }
        if ($this->formId){
            //取得form_id后，删除原有记录
            TemplateService::deleteByFormId($this->formId);
        }

        return [
            'touser' => $this->openId ?? $this->touser,
            'template_id' => $this->templateId,
            'page' => $this->page,
            'form_id' => $this->formId,
            'data' => $this->formatData()
        ];
    }

    /**
     * @return mixed
     */
    public function getUrl()
    {
        if (!$this->accessToken){
            $this->accessToken = '自定义token，需要实现';
        }
        $url = $this->url ?? config('template.url','');
        return str_replace(':access_token',$this->accessToken, $url);
    }

    /**
     *
     * @return array
     */
    public function formatData()
    {
        $return = [];
        if (is_string($this->data)){
            $this->data = json_decode($this->data, true);
        }
        if (is_array($this->data)){
            $n = 0;
            $key = '';
            foreach ($this->data as $index => $value) {
                $n += 1;
                $key = 'keyword' . $n;
                $return[$key] = [
                    'value' => $value
                ];
            }
        }
        return $return;
    }

    /**
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * @return string
     */
    public function getFormId()
    {
        return $this->formId;
    }

    /**
     * $placeholder_params = [
     *     ':abc' => 'def',
     *     ‘:string’ => 'this is string'
     * ];
     * @param array $placeholder_params
     */
    public function parseTemplatePlaceholder($placeholder_params = [])
    {
        if (is_array($this->data)){
            $this->data = json_encode($this->data);
        }

        $placeholder_params = $placeholder_params ?: $this->placeholder_params;
        //此刻要保证$this->data是一个原始的值
        foreach ($placeholder_params as $placeholder => $value) {
            $this->data = str_replace($placeholder, $value, $this->data);
        }
    }
}